package edu.buu.refectory.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;


/**
 * 文件处理工具类.
 *
 * @author Henley<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2016-01-18 <br>
 */
public class FileUtil {

	/** The excel mode. */
	public static String[][] excelMode;

	/** The log. */
	private static Logger log = Logger.getLogger(FileUtil.class);

    /** The Constant pathConfig. */
    //文件配置路径
    public static final String pathConfig = "piano.properties";
    
	/**
	 * 文件下载.
	 *
	 * @param request the request
	 * @param response the response
	 * @param fileName the file name
	 * @throws UnsupportedEncodingException the unsupported encoding exception
	 */
	public static void download(HttpServletRequest request,
			HttpServletResponse response, String fileName)
			throws UnsupportedEncodingException {

		response.setContentType("text/html;charset=UTF-8");
		try {

			File file = new File(PropertiesUtil.getFilePath() + fileName);
			InputStream fis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			response.addHeader("Content-disposition",
					"attachment;filename=\""
							+ new String(file.getName().getBytes("gb2312"),
									"ISO8859-1"));

			response.addHeader("Content-Length", "" + file.length());

			OutputStream os = new BufferedOutputStream(response.getOutputStream());
			os.write(buffer);
			os.flush();
			os.close();
		} catch (IOException ex) {
            log.error("下载文件异常[" + ex.getMessage() + "]");
		}
	}

    /**
     * 文件上传.
     *
     * @param request the request
     * @return the string
     * @throws FileUploadException the file upload exception
     * @throws IOException Signals that an I/O exception has occurred.
     * @throws FileNotFoundException the file not found exception
     */
    public static String upload(HttpServletRequest request)
			throws FileUploadException, IOException, FileNotFoundException {
		String path = PropertiesUtil.getFilePath();
		// 文件存放的目录
		File filePath = new File(path);
		if (!filePath.exists()) {
		    filePath.mkdirs();
		}

		// 创建磁盘文件工厂
		DiskFileItemFactory fac = new DiskFileItemFactory();
		// 创建servlet文件上传组件
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		// 文件列表
		List<FileItem> fileList = null;
		// 解析request从而得到前台传过来的文件
		fileList = upload.parseRequest(request);

		// 保存后的文件名
		String fileName = null;
		// 便利从前台得到的文件列表
		Iterator<FileItem> it = fileList.iterator();

		while (it.hasNext()) {
		    FileItem item = it.next();
		    // 如果不是普通表单域，当做文件域来处理
		    if (!item.isFormField()) {
		        String fileType = item.getName().substring(item.getName().lastIndexOf("."));
		        fileName = System.currentTimeMillis() + fileType;
		        BufferedInputStream in = new BufferedInputStream(item.getInputStream());
		        path = path + fileName;
		        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File(path)));
		        Streams.copy(in, bout, true);
		        in.close();
		        bout.close();
		    }
		}
		return fileName;
	}
}
